<template>
  <div class="app-container">
    <el-row style="display: flex; justify-content: space-between">
      <!-- <el-switch
        @change="hidechange"
        v-model="基础项目"
        inactive-text="隐藏基础项目"
      >
      </el-switch>

      <el-switch
        @change="hidechange"
        v-model="不判断"
        style="margin-left: 5px"
        inactive-text="隐藏不判断"
      >
      </el-switch> -->

      <div style="flex: 1">
        <el-input v-model="s" @keyup.enter.native="hidechange" style="width: 350px; margin-left: 10px"
          placeholder="项目名称、评价结果、适配疾病    回车"></el-input>
      </div>

      <div>
        <!-- <el-button type="primary" round @click="addTemplate"
          >添加模板</el-button
        > -->
        <el-button type="primary" round @click="updatePatient">刷新</el-button>
        <!-- <el-button
          type="success"
          @click="查看文件('路径表单')"
          style="margin-left: 5px"
          round
          >路径表单</el-button
        > -->
        <el-button type="success" @click="seeTempInfo" style="margin-left: 5px" round>查看模板明细</el-button>
        <el-button type="danger" style="margin-left: 5px" @click="查看文件('路径方案')" round>路径方案</el-button>
      </div>
    </el-row>
    <el-row>
      <el-table :row-style="rowStyle" :header-cell-style="{ background: '#f2f2f2' }" :data="ls2" border
        :show-summary="true" v-loading="数据加载" :summary-method="summary" style="width: 100%" max-height="600">
        <!-- <el-table-column type="selection" width="55"> </el-table-column> -->
        <el-table-column fixed prop="类型" label="收费类别" width="100">
          <template #header>
            <el-select v-model="typeValue" @change="changeOption('类型', $event)" clearable placeholder="请选择类型">
              <el-option v-for="(item, index) in typeOption" :key="index" :label="item" :value="item">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column fixed prop="项目名称" label="项目名称" width="320">
          <template slot-scope="scope">
            <div class="item-cell">
              <el-tooltip v-if="scope.row.适用范围" class="item" effect="dark" placement="top-start">
                <div slot="content" v-html="适用范围content(scope.row)"></div>
                <span class="item-name">{{ scope.row.项目名称 }} </span>
              </el-tooltip>
              <span class="item-name" v-else>{{ scope.row.项目名称 }} </span>
              <span class="add-btn" @click="addTemplate(scope.row)">添加</span>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="医保属性" label="医保属性"> </el-table-column> -->
        <el-table-column prop="单价" label="单价" width="80"> </el-table-column>
        <el-table-column prop="数量" label="数量" width="80"> </el-table-column>
        <el-table-column prop="金额" label="金额（元）" width="120">
        </el-table-column>
        <el-table-column prop="属性" :formatter="项目属性fmt" label="项目属性" width="150">
          <template #header>
            <el-select @change="changeOption('属性', $event)" clearable v-model="attributeValue" placeholder="请选择属性">
              <el-option v-for="item in attributeOption" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="结果含义" label="评价结果" width="150">
          <template #header>
            <el-select @change="changeOption('结果含义', $event)" clearable v-model="resultValue" placeholder="请选择结果">
              <el-option v-for="(item, index) in resultOption" :key="index" :label="item" :value="item">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="可优化金额" label="可优化金额" width="120">
        </el-table-column>
        <el-table-column prop="限制" label="限制" width="80">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.限制说明" Left="提示文字" placement="top-start">
              <span style="color: red">{{ scope.row.限制 }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="并发症消耗" label="并发症消耗" width="120">
                </el-table-column> -->
        <el-table-column prop="路径名称" label="适配疾病" width="250">
          <template #header>
            <el-select @change="changeOption('路径名称', $event)" clearable v-model="diseaseValue" placeholder="请选择适配疾病">
              <el-option v-for="(item, index) in diseaseOption" :key="index" :label="item" :value="item">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column :formatter="类别费用fmt" prop="类别费用" label="类别费用小计（元）" width="100">
        </el-table-column>
        <el-table-column prop="类别占比" :formatter="类别占比fmt" label="类别占比" width="100">
        </el-table-column>
      </el-table>
    </el-row>
    <el-row>
      <el-descriptions v-if="warnMsg" title="温馨提示" :column="1" :colon="false">
        <el-descriptions-item label="">
          <div style="width: 100%; display: flex; justify-content: space-between">
            <!-- <div style="color: red" v-html="warnMsg"></div> -->
            <div style="color: red">
              <div v-for="(item, index) in warnMsgs" :key="index" style="display: flex; align-items: center">
                {{ `${index + 1}.${item}` }}
                <span v-if="isShowQue(item)" style="display: flex; align-items: center; cursor: pointer">
                  <img @click="openMsg(isShowQue(item))" style="width: 20px; height: 20px" class="pic-404__parent"
                    src="@/assets/img/yiwen.png" />
                </span>
              </div>
            </div>
            <div class="remark-box" v-if="rolesId == 5 || rolesId == 9">
              <div class="msg">
                医保管理员可以录入批注，当事医生可以在消息管理中回复。
                <img v-if="!remarkInfo" @click="isEditRemark = true" style="width: 24px; cursor: pointer"
                  :src="require('@/assets/img/liuyan-icon.png')" />
              </div>
              <div class="remark-inp">
                <div class="has-remark" v-if="!isEditRemark && remarkInfo">
                  <span>{{ remarkInfo.msg }}</span>
                  <el-tooltip v-if="remarkInfo.rmsg" class="item" effect="dark" :content="remarkInfo.rmsg"
                    placement="top">
                    <span class="hasrmsg">已回复</span>
                  </el-tooltip>
                  <el-button style="margin-left: 10px"
                    @click="(isEditRemark = true), (remarkInp = remarkInfo.msg)">编辑</el-button>
                </div>
                <div v-if="isEditRemark" style="display: flex">
                  <el-input style="min-width: 400px" :autosize="{ minRows: 3, maxRows: 8 }" type="textarea"
                    placeholder="请输入留言" v-model="remarkInp"></el-input>
                  <div style="display: flex">
                    <el-button style="margin-left: 10px; max-height: 45px" @click="cancelSubmit(0)">取消</el-button>
                    <el-button style="max-height: 45px" @click="cancelSubmit(1)" type="primary">保存</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="基本信息">
        <el-descriptions-item label="科室">
          {{ patinfo.科室 }}
        </el-descriptions-item>

        <el-descriptions-item label="姓名">
          {{ `${patinfo.patname} ，${patinfo.gender}，${patinfo.age}` }}
        </el-descriptions-item>

        <el-descriptions-item label="住院号">
          {{ patinfo.fno }}
        </el-descriptions-item>

        <el-descriptions-item label="床位号">
          {{ patinfo.床号 }}
        </el-descriptions-item>

        <el-descriptions-item label="主管医生">
          {{ patinfo.医生 }}
        </el-descriptions-item>

        <el-descriptions-item label="入院日期">
          {{ patinfo.itime }}
        </el-descriptions-item>
        <el-descriptions-item label="刷新时间">
          {{ patinfo.rtime }}
        </el-descriptions-item>
        <el-descriptions-item label="出院日期">
          {{ patinfo.otime }}
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="入组情况" style="position: relative">
        <el-descriptions-item label="入组">
          {{ patinfo.drgcode }}-{{ patinfo.drgname }}
          <el-button style="position: absolute; left: 75px; top: -6px" size="mini" type="primary" plain
            @click="openEditGroup">预分组测试</el-button>
          <el-tooltip class="item msg-icon" effect="dark" content="查看分组详情" placement="top">
            <img v-if="patinfo.error" @click="showGroupInfo = true" style="width: 20px; height: 20px"
              class="pic-404__parent" src="@/assets/img/gantan.png" />
          </el-tooltip>
        </el-descriptions-item>

        <el-descriptions-item label="主要诊断">
          <el-link type="primary" @click="执行情况(诊断Obj.m)">{{ 诊断Obj.m.疾病编码 }}-{{ 诊断Obj.m.诊断名称 }}
            <span v-if="诊断Obj.m.并发症状态">-{{ 诊断Obj.m.并发症状态 }}</span>
          </el-link>
        </el-descriptions-item>
        <el-descriptions-item label="其他诊断">
          <template v-for="it in 诊断Obj.ols">
            <el-link v-if="it.版本ID" type="primary" style="margin-right: 5px;white-space: nowrap;" v-bind:key="it.诊断名称"
              @click="执行情况(it)">{{ it.诊断名称
              }}<span v-if="it.并发症状态">({{ it.并发症状态 }})</span></el-link>
            <span style="margin-right: 5px;" v-bind:key="it.诊断名称" v-else>{{ it.诊断名称 }}
              <span v-if="it.并发症状态">({{ it.并发症状态 }})</span></span>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="主要手术">
          {{ patinfo.optcode }}-{{ patinfo.optname }}
        </el-descriptions-item>
        <el-descriptions-item label="其他手术">
          {{ patinfo.其他手术名称 }}
        </el-descriptions-item>
      </el-descriptions>

      <el-descriptions title="费用情况">
        <el-descriptions-item label="总费用">
          <span v-bind:style="stdCss(patinfo.cost, 获取界面标杆费用().平均费用)">
            {{ patinfo.cost }}/{{ 获取界面标杆费用().平均费用 || 0 }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="床日">
          <span v-bind:style="stdCss(patinfo.bed, 获取界面标杆费用().平均床日)">
            {{ patinfo.bed }}/{{ 获取界面标杆费用().平均床日 || 0 }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="药品费">
          <span v-bind:style="stdCss(
            patinfo.expendedZ || patinfo.expended,
            获取界面标杆费用().平均药品费
          )
            ">
            {{
              patinfo.expendedZ
              ? `${patinfo.expendedZ}(${patinfo.中药主诊断金额 || 0})+${patinfo.expendedC || 0}(${patinfo.中药次诊断金额||0})`
              : patinfo.expended
            }}/{{ 获取界面标杆费用().平均药品费 || 0 }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="检验">
          <span v-bind:style="stdCss(
            patinfo.surveyfeeZ || patinfo.surveyfee,
            获取界面标杆费用().平均检验费
          )
            ">
            {{
              patinfo.surveyfeeZ
              ? `${patinfo.surveyfeeZ}+${patinfo.surveyfeeC || 0}`
              : patinfo.surveyfee
            }}/{{ 获取界面标杆费用().平均检验费 || 0 }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="检查">
          <span v-bind:style="stdCss(
            patinfo.examfeeZ || patinfo.examfee,
            获取界面标杆费用().平均检查费
          )
            ">
            {{
              patinfo.examfeeZ
              ? `${patinfo.examfeeZ || 0}+${patinfo.examfeeC || 0}`
              : patinfo.examfee
            }}/{{ 获取界面标杆费用().平均检查费 || 0 }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="治疗">
          <span v-bind:style="stdCss(
            patinfo.治疗费Z || patinfo.治疗费,
            获取界面标杆费用().平均治疗费
          )
            ">
            {{
              patinfo.治疗费Z
              ? `${patinfo.治疗费Z}+${patinfo.治疗费C || 0}`
              : patinfo.治疗费
            }}/{{ 获取界面标杆费用().平均治疗费 || 0 }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="手术">
          <span v-bind:style="stdCss(
            patinfo.optfeeZ || patinfo.optfee,
            获取界面标杆费用().平均手术费
          )
            ">
            {{
              patinfo.optfeeZ
              ? `${patinfo.optfeeZ}+${patinfo.optfeeC || 0}`
              : patinfo.optfee
            }}/{{ 获取界面标杆费用().平均手术费 || 0 }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="耗材">
          <span v-bind:style="stdCss(
            patinfo.matfeeZ || patinfo.matfee,
            获取界面标杆费用().平均耗材费
          )
            ">
            {{
              patinfo.matfeeZ
              ? `${patinfo.matfeeZ}+${patinfo.matfeeC || 0}`
              : patinfo.matfee
            }}/{{ 获取界面标杆费用().平均耗材费 || 0 }}
          </span>
        </el-descriptions-item>

        <el-descriptions-item label="并发症额度">
          <span v-bind:style="stdCss(patinfo.并发症实际消耗, patinfo.并发症理论额度)
            ">
            {{ patinfo.并发症实际消耗 || 0 }}/{{ patinfo.并发症理论额度 || 0 }}
          </span>
        </el-descriptions-item>
      </el-descriptions>
    </el-row>
    <el-row>
      <el-dialog :title="'[' + patinfo.fno + ']' + dialogTitle + ' 临床路径执行情况'" :visible.sync="dialogVisible" width="60%">
        <el-row>
          <el-link type="primary" @click="执行_filter()" style="float: right">
            {{ 执行or全部 ? "全部" : "仅看未执行" }}
          </el-link>
        </el-row>
        <el-row>
          <el-table :data="执行情况Ls" border style="width: 100%" height="600">
            <el-table-column prop="类型" label="类型" width="80">
            </el-table-column>
            <el-table-column prop="项目名称" label="项目名称" width="280">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="scope.row.适用范围" placement="top-start">
                  <span>{{ scope.row.项目名称 }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="属性" label="选择属性"> </el-table-column>
            <el-table-column prop="限制" label="限制" width="80">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="scope.row.限制说明" Left="提示文字" placement="top-start">
                  <span style="color: red">{{ scope.row.限制 }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="缺省" label="缺省优先">
              <template slot-scope="scope">
                {{ scope.row.缺省 ? "缺省" : "" }}
              </template>
            </el-table-column>
            <el-table-column prop="组号" label="组号"> </el-table-column>
            <el-table-column prop="是否执行" label="执行情况">
            </el-table-column>
          </el-table>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">关 闭</el-button>
        </span>
      </el-dialog>
    </el-row>

    <el-row>
      <el-dialog :close-on-click-modal="false" :title="uploadTitle" :visible.sync="uploadDialogVisible" width="40%"
        :before-close="handleClose">
        <el-input v-model="searchName" placeholder="请输入关键字搜索" @change="searchFiles"></el-input>
        <div style="
            min-height: 200px;
            max-height: 500px;
            overflow: auto;
            margin-top: 10px;
          ">
          <el-empty v-if="!文件s.length" description="暂无数据"></el-empty>
          <ul v-else class="el-upload-list el-upload-list--text">
            <li v-for="f in 文件s" v-bind:key="f.name" class="el-upload-list__item is-ready">
              <a class="el-upload-list__item-name" target="_blank" :href="downLoadUrl + '/' + f.url"><i
                  class="el-icon-document"></i>{{ f.name }}</a>
            </li>
          </ul>
        </div>
      </el-dialog>
      <el-dialog title="添加到模板" :visible.sync="isOpenAddTemplate" width="30%" :before-close="closeAddTemplate">
        <div style="
            display: flex;
            padding: 0 20px;
            align-items: center;
            width: 100%;
          ">
          <span style="flex-shrink: 0" class="item-label">请选择：</span>
          <el-select v-model="selectTemp" multiple collapse-tags style="margin-left: 20px; width: 100%" placeholder="请选择">
            <el-option v-for="(item, index) in templateOptions" :key="index" :label="item.版本名称" :value="item.版本ID">
            </el-option>
          </el-select>
        </div>
        <div style="
            display: flex;
            padding: 0 20px;
            align-items: center;
            width: 100%;
          ">
          <span style="flex-shrink: 0" class="item-label"></span>
          <div style="margin-top: 20px; margin-left: 20px">
            <el-checkbox v-model="checked">添加到相关模板 </el-checkbox>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="closeAddTemplate">取 消</el-button>
          <el-button type="primary" @click="confirmAddTemplate">确 定</el-button>
        </span>
      </el-dialog>
    </el-row>
    <el-dialog :visible.sync="queVisible" width="800px" :before-close="closeTable">
      <el-table border :data="queTable" style="width: 100%" v-loading="loading">
        <el-table-column prop="诊断" label="诊断" v-if="msgType === 2" width="300"></el-table-column>
        <el-table-column v-if="msgType === 3" prop="诊断名称" label="资源消耗最多的诊断"></el-table-column>
        <template v-if="msgType === 2 || msgType === 1">
          <el-table-column prop="项目类型" label="项目类型"> </el-table-column>
          <el-table-column prop="项目名称" label="项目名称" width="300">
          </el-table-column>
          <el-table-column prop="状态" label="状态"> </el-table-column>
        </template>
        <el-table-column v-if="msgType === 5" prop="提示" label="提示">
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog title="分组情况" center :visible.sync="showGroupInfo" width="600px">
      <div v-if="patinfo.error === '成功'">
        <div style="margin-bottom: 10px">成功</div>
        <div>***{{ patinfo.drgcode }}-{{ patinfo.drgname }}***</div>
      </div>

      <div v-else-if="isJson(patinfo.error)">
        <div style="margin-bottom: 10px" v-for="(item, index) in isJson(patinfo.error)" :key="index">
          {{ item }}
        </div>
      </div>
      <div v-else-if="patinfo && patinfo.error && patinfo.error.substring(0, 1) === '['
        ">
        <div style="margin-bottom: 10px" v-for="(item, index) in patinfo.error.split(',')" :key="index">
          {{
            index === 0
            ? item.substr(1)
            : index === patinfo.error.split(",").length - 1
              ? item.substring(0, item.length - 1)
              : item
          }}
        </div>
      </div>
      <div v-else>其他内容</div>
    </el-dialog>
    <GroupDialog ref="groupDialog" :visible.sync="groupVisible" />
    <el-dialog :title="tplInfo.名称 ? `${tplInfo.名称}详情` : ''" :visible.sync="tempInfosVisible" width="1200px">
      <el-tabs v-model="activeName">
        <el-tab-pane label="本院" name="1"></el-tab-pane>
        <el-tab-pane label="外院" name="2"></el-tab-pane>
      </el-tabs>
      <el-table v-show="activeName === '1'" border :show-summary="true" :summary-method="getSummaries" max-height="600"
        :data="tempInfos" :header-cell-style="{ background: '#f2f2f2' }" style="width: 100%">
        <el-table-column prop="类别" label="类别"> </el-table-column>
        <el-table-column prop="项目名称" label="项目名称" width="300">
          <template slot-scope="{ row }">
            <p>{{ row.项目名称 }} <span v-if="row.规格">：{{ row.规格 }}</span></p>
            <p>{{ row.产地 }}</p>
          </template>
        </el-table-column>
        <el-table-column prop="单价" label="单价"> </el-table-column>
        <el-table-column prop="数量" label="数量"> </el-table-column>
        <el-table-column prop="金额" label="金额"> </el-table-column>
        <!-- <el-table-column prop="项目属性" label="项目属性"> </el-table-column> -->
        <el-table-column prop="选择属性" label="选择属性">
          <template slot-scope="{ row }">
            <span>{{ row.选择属性 ? "必选" : "可选" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="缺省" label="缺省">
          <template slot-scope="{ row }">
            <span>{{ row.缺省 ? "是" : "否" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="模板费用" label="分类费用"> </el-table-column>
      </el-table>
      <el-table v-show="activeName === '2'" border :show-summary="true" :summary-method="getSummaries" max-height="600"
        :data="tempInfos2" :header-cell-style="{ background: '#f2f2f2' }" style="width: 100%">
        <el-table-column prop="类别" label="类别"> </el-table-column>
        <el-table-column prop="项目名称" label="项目名称" width="300">
        </el-table-column>
        <el-table-column prop="单价" label="单价"> </el-table-column>
        <el-table-column prop="数量" label="数量"> </el-table-column>
        <el-table-column prop="金额" label="金额"> </el-table-column>
        <!-- <el-table-column prop="项目属性" label="项目属性"> </el-table-column> -->
        <el-table-column prop="选择属性" label="选择属性">
          <template slot-scope="{ row }">
            <span>{{ row.选择属性 ? "必选" : "可选" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="缺省" label="缺省">
          <template slot-scope="{ row }">
            <span>{{ row.缺省 ? "是" : "否" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="模板费用" label="分类费用"> </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import {
  patResult,
  patientinfo,
  PatWarning,
  zd2path,
  proljzxqk,
  addInTemplate,
  sync,
  getRemark,
  saveRemark,
  editRemark,
  PgjgDetial,
} from "@/api/patient";
import { GetTplById, TplStd } from "@/api/pathway";

import {
  drgInfo,
  drgweightbyid,
  tplDetail,
  tplDetail2,
} from "@/api/PathTemplate";
import { UserModule } from "@/store/modules/user";
import { LsFiles, DestoryFile, listFiles } from "@/api/commonApi";
import GroupDialog from "./groupDialog.vue";

@Component({
  name: "evaluate2",
  components: {
    GroupDialog,
  },
})
export default class extends Vue {
  private activeName: any = "1";
  private querys: any = {};
  private 草药费: any = 0;
  private async created() {
    const localQeury = localStorage.getItem("querys") as any;
    if (localQeury && localQeury.id) {
      this.querys = localQeury;
    }
    // let id: any = this.$route.query.id || "1079886-1";
    if (this.$route.query.id) {
      localStorage.setItem("querys", this.$route.query as any);
      this.querys = this.$route.query;
    }
    this.getInfoRemark();
    let id = this.querys.id;
    await this.loadPatinfo(id);
    
    await this.获取并设置诊断关系(id);
    await this.loadPatResult(id);
    this.loadWarning(id);
    //this.草药费 = this.ls.filter((it: any) => it.类型 == '草药').map(it => it.金额).reduce((a, b) => a + b, 0);
    //console.log('草药费',this.草药费)
  }
  private 适用范围content(row: any) {
    return row.类型 === "药品"
      ? `<span style="font-weight:bold;">${row.生产厂家} ${row.规格}</span><p>${row.适用范围}</p>`
      : `<p>${row.适用范围}</p>`;
  }
  get rolesId() {
    return UserModule.rolesId;
  }
  private groupVisible = false;
  private showGroupInfo = false;
  private searchName = "";
  private checked = "";
  private closeTable() {
    this.queVisible = false;
    this.queTable = [];
  }
  private loading = false;
  // private rolesId: any = UserModule.rolesId;
  private remarkInfo: any = null;
  private remarkInp: any = "";
  private isEditRemark: boolean = false;
  private downLoadUrl = `${(<any>window).MyConf.APISERVICE}/files/`;

  public dialogVisible: boolean = false;

  public 诊断Obj = { m: {}, ols: [] };

  public 执行or全部: boolean = false;

  private 文件s: Array<any> = [];

  private uploadDialogVisible: boolean = false;
  private uploadTitle: string = "";
  private openEditGroup() {
    this.groupVisible = true;
    const diagnostics = this.allTempLate;
    const operations = [
      { optcode: this.patinfo.optcode, optname: this.patinfo.optname },
    ];

    //设置基本信息
    (this.$refs.groupDialog as any).initData(
      this.patinfo,
      diagnostics,
      operations
    );
  }
  private getSummaries(param) {
    const { columns, data } = param;
    const sums = [];
    columns.forEach((column, index) => {
      if (index === 0) {
        sums[index] = "合计";
        return;
      }
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
      } else {
        sums[index] = "";
      }
      if (column.label !== "金额") {
        sums[index] = "";
      } else {
        sums[index] = sums[index] ? sums[index]?.toFixed(2) : "";
      }
    });

    return sums;
  }
  private async cancelSubmit(type) {
    if (!type) {
      this.isEditRemark = false;
      this.remarkInp = "";
      return;
    }
    if (!this.remarkInp) {
      return this.$message.warning("请输入留言");
    }
    const params = this.remarkInfo
      ? {
        id: this.remarkInfo.id,
        msg: this.remarkInp,
      }
      : {
        msg: this.remarkInp,
        jzh: this.querys.id,
        fsr: UserModule.name,
        jsr: this.patinfo.医生,
      };
    //保存留言
    this.remarkInfo ? await editRemark(params) : await saveRemark(params);
    this.$message.success("操作成功");
    this.isEditRemark = false;
    this.getInfoRemark();
  }
  private isJson(text) {
    if (!text) return "";
    try {
      const res = JSON.parse(text);
      return res.Message;
    } catch (error) {
      return "";
    }
  }
  private async getInfoRemark() {
    console.log(this.querys, "querys");

    const res = await getRemark({
      fsr: UserModule.name,
      jzh: this.querys.id,
      jsr: "",
      zt: "",
    });
    if (!res.data.length) return;
    this.remarkInfo = res.data[0];
    this.remarkInp = res.data[0].msg;
  }
  private handleClose() {
    this.searchName = "";
    this.uploadDialogVisible = false;
  }
  private async updatePatient() {
    const id: any = this.querys.id;
    const patname = this.querys.patname;
    const loading = this.$loading({
      text: `正在刷新【${patname}】.....^_^`,
      lock: true,
      background: "rgba(255, 255, 255, 0.1)",
    });
    sync({ id }).then(async (d: any) => {
      this.$message({
        type: "success",
        message: `【${patname}】刷新成功!`,
      });
      loading.close();
      this.loadPatResult(id);
      this.loadPatinfo(id);
      await this.获取并设置诊断关系(id);
      this.loadWarning(id);
    });
  }
  //改变选项筛选数据
  private changeOption(key, e) {
    if (e || e === 0) {
      //如果存在相同的筛选条件先删除 再添加新的
      if (this.filterQuery.some((v) => v.key == key)) {
        this.filterQuery = this.filterQuery.filter((v) => v.key != key);
      }
      this.filterQuery.push({ key, value: e });
    } else {
      this.filterQuery = this.filterQuery.filter((v) => v.key != key);
    }
    //筛选数据
    console.log(this.filterQuery);

    let filterData = this.ls;
    if (!this.filterQuery.length) {
      filterData = this.ls;
    } else {
      filterData = this.filterQuery.reduce((pre, cur) => {
        const res = pre.filter((v) => v[cur.key] == cur.value);
        return res;
      }, this.ls);
    }
    console.log(filterData, "结果----------");
    this.ls2 = filterData;
  }
  private async 查看文件(t: string, txt: any = '') {
    let ts = [this.诊断Obj.m, ...this.诊断Obj.ols];
    this.uploadTitle = t;
    let 版本s = ts
      .filter((it: any) => it && it.版本ID)
      .map((it: any) => it.版本ID);
    if (!版本s?.length) {
      return this.$message.warning("系统无对应参考模板！");
    }
    this.uploadDialogVisible = true;
    let 文件目录: any = Array.from(
      new Set(版本s.flatMap((it: any) => [`${it}-${t}`]))
    ).join(",");
    // const { data } = await LsFiles({ tpl: 文件目录 });
    let d = await listFiles({ tpl: 文件目录, name: this.searchName });
    let data = d.data;
    if (txt.trim()) data = (data || [{ name: '', url: '' }]).filter((it: any) => it.name.indexOf(txt) > -1);
    this.文件s = data;
  }
  public 执行_filter() {
    this.执行or全部 = !this.执行or全部;
    if (this.执行or全部) {
      this.执行情况Ls = this.执行情况Ls2.filter(
        (it: any) => it.是否执行 !== "已执行"
      );
    } else {
      this.执行情况Ls = this.执行情况Ls2.map((it: any) => it);
    }
  }
  public 执行情况Ls: Array<any> = [];
  public 执行情况Ls2: Array<any> = [];
  public dialogTitle: string = "";
  public async 执行情况(r: any) {
    let 版本本id = r.版本ID;
    let id = this.patinfo.id;
    if (r.是否主诊断) {
      this.dialogTitle = r.诊断名称;
    } else this.dialogTitle = `次要诊断` + r.诊断名称;
    const { data } = await proljzxqk({ pid: 版本本id, id: id });
    this.执行情况Ls = data;
    this.执行情况Ls2 = data;
    this.dialogVisible = true;
  }
  private async 获取并设置诊断关系(id: string) {
    let data: any = await zd2path({ id: id });
    data = data.data;
    data = data || [];
    //筛选出有模板的数据
    this.templateOptions = data.filter((v) => v.版本ID);
    this.allTempLate = data;
    let 主要诊断 = data.filter((it: any) => it.是否主诊断);
    if (主要诊断.length > 0) 主要诊断 = 主要诊断[0];
    else {
      主要诊断 = {};
    }
    let 其他诊断s = data.filter((it: any) => !it.是否主诊断);
    let o = { m: 主要诊断, ols: 其他诊断s };
    this.诊断Obj = o;
  }
  public queVisible = false;
  public queTable: Array<any> = [];
  private msgType = 1;
  public async openMsg(type) {
    this.queVisible = true;
    this.msgType = type;
    this.loading = true;
    const res = await PgjgDetial({
      tp: type,
      param: this.querys.id,
    });
    this.queTable = res.data;
    this.loading = false;
  }
  public searchFiles(e: any) {
    //console.log(e, "eeee");
    this.查看文件("路径方案", e);
  }
  public isShowQue(item) {
    const reg1 = new RegExp("主要诊断依据不足");
    const reg2 = new RegExp("其他诊断依据不足");
    const reg3 = new RegExp("主要诊断选择疑视违反核心治疗，请正确选择主要诊断");
    const reg5 = new RegExp("清单校验失败");
    const hasText1 = reg1.test(item);
    const hasText2 = reg2.test(item);
    const hasText3 = reg3.test(item);
    const hasText5 = reg5.test(item);
    if (hasText1) return 1;
    if (hasText2) return 2;
    if (hasText3) return 3;
    if (hasText5) return 5;
    return "";
  }
  public warnMsg = "";
  public warnMsgs = [];
  private async loadWarning(id: string) {
    const { data } = await PatWarning({ id: id });
    let ts = (data || [])
      .filter((it: any) => it != null)
      .map((it: any, i: number) => `${(it || {}).M}`)
      .join(";");
    if (ts.length > 0)
      this.warnMsg = ts
        .split(";")
        .map((it: any, i: number) => `${i + 1}、${it}`)
        .join("<br/>");
    this.warnMsgs = ts.split(";");
    //this.warnMsg = '病种成本过大，药品（耗材）占比过高。;并发症消耗过大，理论值2133.23元，实际5923.31元。;1.35倍率，费用超标，存在亏损风险。'
  }

  public s: string = "";

  public stdCss(v1: number, v2: number) {
    if (!v1 || !v2) return {};
    if (v1 / v2 > 1.2) {
      return { color: "red" };
    } else if (v1 / v2 < 0.8) {
      return { color: "blue" };
    }
    return {};
  }
  public rowData: any = {};
  public isOpenAddTemplate: Boolean = false;
  public templateOptions: Array<any> = [];
  public allTempLate: Array<any> = [];
  public selectTemp: Array<any> = [];
  public selectTable: Array<any> = [];
  public ls2: Array<any> = [];
  public typeValue: String = "类型";
  public typeOption: Array<any> = [];
  public resultValue: String = "评价结果";
  public resultOption: Array<any> = [];
  public diseaseValue: String = "适配疾病";
  public diseaseOption: Array<any> = [];
  public attributeValue: String = "项目属性";
  public attributeOption: Array<any> = [];
  public filterQuery: Array<any> = [];
  public hidechange() {
    let ts = this.ls;
    if (this.基础项目) {
      ts = ts.filter((it: any) => it.属性 !== 1);
    }
    if (this.不判断) {
      ts = ts.filter((it: any) => it.属性 !== 2);
    }
    if (this.s) {
      ts = ts.filter(
        (it: any) =>
          it.项目名称.indexOf(this.s) > -1 ||
          it.结果含义.indexOf(this.s) > -1 ||
          it.路径名称.indexOf(this.s) > -1
      );
    }
    this.ls2 = ts;
  }

  public 基础项目: boolean = false;

  public 不判断: boolean = false;

  public rowStyle(r: any) {
    const { row, index } = r;
    let o: any = {
      漏做: "purple",
      超范围: "#FF8000",
      不匹配: "red",
      非最佳: "blue",
      超模板金额: "#F00078",
      非最优: "#FF60AF",
    };
    if (o[row.结果含义]) {
      return { color: o[row.结果含义], "font-weight": "bold" };
    }
    return {};
  }
  public patinfo: any = {};
  public std: any = {};
  public hisstd: any = {};
  public tplInfo: any = {};
  public tempInfos: any = [];
  public tempInfos2: any = [];
  public tempInfosVisible: any = false;
  private handleSelectionChange(e) {
    this.selectTable = e;
  }
  private addTemplate(row) {
    // if (!this.selectTable.length) return this.$message.error("请选择数据");
    this.rowData = row;
    this.isOpenAddTemplate = true;
  }
  private closeAddTemplate() {
    this.isOpenAddTemplate = false;
    this.selectTemp = [];
  }
  private async confirmAddTemplate() {
    if (!this.selectTemp.length) return this.$message.warning("请选择模板");
    const v = this.rowData;
    //筛选出选中项
    const selectTemps = this.allTempLate.filter((v) =>
      this.selectTemp.includes(v.版本ID)
    );
    const params = {
      isAdd: this.checked ? 1 : 0,
      item: {
        xmid: v.项目ID,
        xmmc: v.项目名称,
        type: v.类型,
        sl: v.数量,
        dj: v.单价,
        ljid: v.路径id,
      },
      template: selectTemps.map((v) => ({
        tempId: v.版本ID,
        tempName: v.版本名称,
      })),
    };
    console.log(params, "params---------");

    const res = await addInTemplate(params);
    this.$message.success(res.data || "操作成功");
    this.closeAddTemplate();
  }
  private async loadTplStd(tplid: string) {
    const { data } = await TplStd({ tplid: tplid });
    let std = data || {};
    let o: any = {};
    Object.keys(std).forEach((k: string) => {
      o[`平均${k}费`] = std[k];
    });

    this.hisstd = o;
  }
  private changeStatus(status, e) {
    this.ls2.forEach((v, i) => {
      if (v.ID === e.ID) {
        v.isShowAdd = status;
        this.$set(this.ls2, i, v);
      }
    });
  }
  //所有标杆值
  private allStds: Array<any> = [];
  private async loadPatinfo(id: string) {
    const { data } = await patientinfo({ id: id });
    this.patinfo = data;
    let dd: any = await GetTplById({ id: this.patinfo.版本ID });
    dd = (dd.data || {}).tpl || {};
    this.tplInfo = dd;
    await this.loadTplStd(this.patinfo.版本ID);
    let 来源 = "市级标杆";
    if (this.patinfo.drgcode) {
      let d: any = await drgweightbyid({
        code: this.patinfo.drgcode,
        wid: this.patinfo.路径ID,
      });
      d = d.data;
      this.allStds = d || [];
      this.allStds.forEach((it: any) => {
        it.平均费用 = it.标准总费用;
        Object.keys(it).forEach((k: string) => {
          if (k.startsWith("标准")) {
            let k2 = k.replace("标准", "平均");
            it[k2] = it[k];
          }
        });
      });
      let ts = this.allStds.filter((it: any) => it.标杆类型 == 来源);
      let ts2 = this.allStds.filter((it: any) => it.版本 == "本院标杆");
      if (ts.length > 0) {
        this.std = ts[0];
      }
      if (ts2.length > 0) {
        this.hisstd = ts2[0];
      }
    }
  }

  public 数据加载: boolean = false;
  public ls: Array<any> = [];

  public summary(r: any) {
    const { columns, data } = r;
    let sums: any = [];

    columns.forEach((it: any, index: number) => {
      if (index == 0) sums[index] = "合计";
      else if (it.property == "可优化金额") {
        let sum = data
          .filter((it2: any) => it2[it.property])
          .map((it2: any) => it2[it.property])
          .reduce((a: number, b: number) => a + b, 0);
        sums[index] = sum.toFixed(2);
      } else if (it.property == "金额") {
        let 类型s = Array.from(new Set((data || []).map((it: any) => it.类型)));
        let 标杆 = this.获取界面标杆费用();

        let sum = data
          .filter((it2: any) => it2.金额)
          .map((it2: any) => it2.金额)
          .reduce((a: number, b: number) => a + b, 0);
        // let sum = 类型s.map((it: any) => (标杆[`平均${it}费`] || 0)).reduce((a: number, b: number) => a + b, 0);
        sums[index] = sum.toFixed(2);
      }
    });
    return sums;
  }
  public 项目属性fmt(row: any, column: any, cellValue: any, index: number) {
    let o: any = {
      4: "非常特征",
      0: "",
      1: "基础项目",
      2: "不判断",
    };

    return o[row.属性] || "";
  }
  public 类别占比fmt(row: any, column: any, cellValue: any, index: number) {
    let 类型 = row.类型;

    let k = `平均${row.类型}费`;
    let 类别费用 = this.ls
      .filter((it: any) => it.类型 == 类型 && it.金额)
      .map((it: any) => it.金额)
      .reduce((a: number, b: number) => a + b, 0);

    let 总费用 = this.ls
      .filter((it: any) => it.金额)
      .map((it: any) => it.金额)
      .reduce((a: number, b: number) => a + b, 0);
    // let 总费用 = this.获取界面标杆费用()[k];
    let v = 0;
    if (总费用) {
      v = (类别费用 / 总费用) * 100;
    }

    row[column.property] = v.toFixed(2);

    return row[column.property];
  }

  private 获取界面标杆费用() {
    let v;

    //1.先获取“选择”滴标杆且审核过的
    let ts = this.allStds.filter((it: any) => it.选择);
    if (ts.length > 0) {
      v = ts[0];
    } else if (
      this.tplInfo.是否审核 &&
      this.patinfo.drgcode == this.tplInfo.分组编码
    ) {
      v = this.hisstd;
    } else {
      v = this.std;
    }
    return v || {};
  }
  public 类别费用fmt(row: any, column: any, cellValue: any, index: number) {
    let 类型 = row.类型;

    let v: any = cellValue;
    let k = `平均${row.类型}费`;
    let 标杆 = this.获取界面标杆费用();
    v = 标杆[k];
    // if (this.tplInfo.是否审核) {
    //     v = this.hisstd[k]
    // } else {
    //     v = this.std[k]
    // }

    let 费用 = this.ls
      .filter((it: any) => it.类型 == 类型 && it.金额)
      .map((it: any) => it.金额)
      .reduce((a: number, b: number) => a + b, 0);
    row[column.property] = 费用.toFixed(2);
    return row[column.property];
  }
  public 单价fmt(row: any, column: any, cellValue: any, index: number) {
    let 金额 = row.金额;
    let 数量 = row.数量;
    if (金额 && 数量) {
      return (金额 / 数量).toFixed(2);
    }
    return 0;
  }
  private async seeTempInfo() {
    this.tempInfosVisible = true;
    //console.log(this.tplInfo, "tplInfo");

    const res = await tplDetail({ tplid: this.tplInfo.id });
    this.tempInfos = res.data || [];
    const res2 = await tplDetail2({ tplid: this.tplInfo.路径ID });
    this.tempInfos2 = res2.data || [];
  }
  private async loadPatResult(id: string) {
    this.数据加载 = true;
    const { data } = await patResult({ id: id });
    this.ls = data || [];
    this.ls2 = this.ls;
    this.数据加载 = false;
    //赋值表头各选项列表
    this.typeOption = [
      ...new Set(data.filter((v) => v.类型).map((v) => v.类型)),
    ];
    const types = {
      4: "非常特征",
      0: "无属性",
      1: "基础项目",
      2: "不判断",
    };
    this.attributeOption = [
      ...new Set(data.filter((v) => v.属性).map((v) => v.属性)),
      0,
    ].map((v: any) => {
      return {
        label: types[v],
        value: v,
      };
    });
    this.resultOption = [
      ...new Set(data.filter((v) => v.结果含义).map((v) => v.结果含义)),
    ];
    this.diseaseOption = [
      ...new Set(data.filter((v) => v.路径名称).map((v) => v.路径名称)),
    ];
  }

  public objectSpanMethod(r: any) {
    const { row, column, rowIndex, columnIndex } = r;

    let cols = ["类型", "类别费用", "类别占比"];

    if (!cols.includes(column.property)) {
      return {
        rowspan: 1,
        colspan: 1,
      };
    }

    if (!this.ls[rowIndex]) {
      // 1列 1行
      return {
        rowspan: 1,
        colspan: 1,
      };
    }

    if (this.ls[rowIndex - 1]) {
      if (
        this.ls[rowIndex][column.property] ==
        this.ls[rowIndex - 1][column.property]
      ) {
        // 0列 0 行
        return {
          rowspan: 0,
          colspan: 0,
        };
      }
    }
    if (this.ls[rowIndex + 1]) {
      if (
        this.ls[rowIndex][column.property] ==
        this.ls[rowIndex + 1][column.property]
      ) {
        let conutRowSpan = 1;
        let countIndex = 1;
        var len = this.ls.length;
        // 往下遍历 重复的列有几个 合并几个
        for (var i = rowIndex; i <= len; i++) {
          // 遍历数组
          if (
            this.ls[rowIndex + countIndex] &&
            this.ls[rowIndex][column.property] ==
            this.ls[rowIndex + countIndex][column.property]
          ) {
            countIndex += 1;
            conutRowSpan += 1;
          } else {
            break;
          }
        }
        // 2列1行
        return {
          rowspan: conutRowSpan,
          colspan: 1,
        };
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.el-link {
  font-size: 16px !important;
  font-weight: bold;
}

.item-cell {
  .add-btn {
    display: none;
    cursor: pointer;
    color: #1890ff;
    font-size: 14px;
  }
}

.item-cell:hover .add-btn {
  display: inline;
}

.remark-box {
  margin-left: 100px;

  .msg {
    color: #ff6600;
    font-size: 12px;
  }

  .remark-inp {
    margin-top: 20px;

    .hasrmsg {
      font-size: 12px;
      background-color: #dff0ff;
      color: #1890ff;
    }
  }
}

.el-descriptions-item__label {
  white-space: nowrap !important;
}

.item-label {
  display: inline-block;
  min-width: 60px;
}

::v-deep .el-descriptions-item_content {
  display: flex;
  align-items: center;
}

.msg-icon {
  // height: 100%;
  margin-left: 5px;
  // display: flex;
  // align-items: center;
}
</style>
